package com.zaoshui.hudada.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zaoshui.hudada.common.ErrorCode;
import com.zaoshui.hudada.constant.CommonConstant;
import com.zaoshui.hudada.exception.BusinessException;
import com.zaoshui.hudada.exception.ThrowUtils;
import com.zaoshui.hudada.model.dto.app.AppQueryRequest;
import com.zaoshui.hudada.model.entity.*;
import com.zaoshui.hudada.model.enums.AppScoringStrategyEnum;
import com.zaoshui.hudada.model.enums.AppTypeEnum;
import com.zaoshui.hudada.model.vo.AppVO;
import com.zaoshui.hudada.model.vo.UserVO;
import com.zaoshui.hudada.service.AppService;
import com.zaoshui.hudada.mapper.AppMapper;
import com.zaoshui.hudada.service.UserService;
import com.zaoshui.hudada.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author lihai
* @description 针对表【app(应用)】的数据库操作Service实现
* @createDate 2024-05-24 16:57:01
*/
@Service
public class AppServiceImpl extends ServiceImpl<AppMapper, App>
    implements AppService{
    @Resource
    private UserService userService;


    /*
    * 校验参数
    * */
    @Override
    public void validApp(App app, boolean add) {
        if (app == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String appName = app.getAppName();
        String appDesc = app.getAppDesc();
        String appIcon = app.getAppIcon();
        Integer appType = app.getAppType();
        Integer scoringStrategy = app.getScoringStrategy();


        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(appName,appDesc,appIcon), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(appName) && appName.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "应用名称过长");
        }
        if (StringUtils.isNotBlank(appDesc) && appDesc.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "应用描述过长");
        }
        AppTypeEnum appTypeEnum = AppTypeEnum.getEnumByValue(appType);
        if(appTypeEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"应用类型不能为空");
        }
        AppScoringStrategyEnum enumByValue = AppScoringStrategyEnum.getEnumByValue(scoringStrategy);
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"评分策略不能为空");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param appQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<App> getQueryWrapper(AppQueryRequest appQueryRequest) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        if (appQueryRequest == null) {
            return queryWrapper;
        }
        Long id = appQueryRequest.getId();
        String appName = appQueryRequest.getAppName();
        String appDesc = appQueryRequest.getAppDesc();
        Integer appType = appQueryRequest.getAppType();
        Integer scoringStrategy = appQueryRequest.getScoringStrategy();
        Integer reviewStatus = appQueryRequest.getReviewStatus();
        String reviewMessage = appQueryRequest.getReviewMessage();
        Long reviewerId = appQueryRequest.getReviewerId();
        Long notId = appQueryRequest.getNotId();
        Long userId = appQueryRequest.getUserId();
        String sortField = appQueryRequest.getSortField();
        String sortOrder = appQueryRequest.getSortOrder();


        //模糊查询
        queryWrapper.like(StringUtils.isNotBlank(appName), "appName", appName);
        queryWrapper.like(StringUtils.isNotBlank(appDesc), "appDesc", appDesc);
        queryWrapper.like(StringUtils.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);

        //精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appType), "appType", appType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public AppVO getAppVO(App app, HttpServletRequest request) {
        AppVO appVO = AppVO.objToVo(app);
        long appId = app.getId();
        // 1. 关联查询用户信息
        Long userId = app.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        appVO.setUser(userVO);
        return appVO;
    }

    @Override
    public Page<AppVO> getAppVOPage(Page<App> appPage, HttpServletRequest request) {
        List<App> appList = appPage.getRecords();
        Page<AppVO> appVOPage = new Page<>(appPage.getCurrent(), appPage.getSize(), appPage.getTotal());
        if (CollUtil.isEmpty(appList)) {
            return appVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = appList.stream().map(App::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<AppVO> appVOList = appList.stream().map(app -> {
            AppVO appVO = AppVO.objToVo(app);
            Long userId = app.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            appVO.setUser(userService.getUserVO(user));

            return appVO;
        }).collect(Collectors.toList());
        appVOPage.setRecords(appVOList);
        return appVOPage;
    }

}




